<?php

class Admin_fileController extends Controller {

    public function listAction() {
        $type = Request::get('type', 'file'); //file/image
        $dir = Request::get('dir', '');
        $file_config = Configure::getConfig('file');
        $dir_path = $dir ? $file_config ['public_path'] . $dir : $file_config ['public_path'];
        $allow_files = substr(str_replace('.', '|', join('', $file_config ['allow_list_' . $type])), 1);
        $list = $this->readFile($dir_path, $allow_files);
        Response::ajax(200, 'success', array(
            'url_path' => $file_config['url_path'],
            'dir' => $dir,
            'list' => $list
        ));
    }

    public function viewAction() {
        
    }

    protected function readFile($dir, $allow_list_file) {
        if (!is_dir($dir)) {
            return array();
        }
        if (substr($dir, strlen($dir) - 1) != '/') {
            $dir .= '/';
        }
        $handle = opendir($dir);
        $files = array(
            'dir' => array(),
            'file' => array()
        );
        while (false !== ($file = readdir($handle))) {
            if ($file == '.' || $file == '..') {
                continue;
            }
            $path = $dir . $file;
            if (is_dir($path)) {
                $files ['dir'][] = array(
                    'name' => iconv('gb2312', 'UTF-8', $file),
                    'type' => 'dir',
                    'ext' => '',
                    'size' => 0,
                    'mtime' => filemtime($path)
                );
            } elseif (preg_match('/\.(' . $allow_list_file . ')$/i', $file)) {
                $files ['file'][] = array(
                    'name' => iconv('gb2312', 'UTF-8', $file),
                    'type' => 'file',
                    'ext' => strtolower(substr(strrchr($file, '.'), 1)),
                    'size' => filesize($path),
                    'mtime' => filemtime($path)
                );
            }
        }
        closedir($handle);
        $files = array_merge($files['dir'], $files['file']);
        return $files;
    }

}
